package iss.java;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import iss.java.list.MyList;
import iss.java.list.Node;

/**
 * Created by wenke on 2016/9/16.
 */
public class Main_B {
    public static void main(String[] args) throws BrokenBarrierException, InterruptedException  {
        // TODO: Write a multithreaded testcase against requirement B.
        // NOTE: Testcase for requirement C is not required.
    	MyList list = new MyList();
    	MyList listB = new MyList();
    	CyclicBarrier barrier = new CyclicBarrier(3);
    	Thread thread1 = new Thread() {
    		public void run() {
    			for(int i = 10; i > 0; i--) {
    				list.insert(list.getHead(), i);
    			}
    			try {
					barrier.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (BrokenBarrierException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    	};
    	Thread thread2 = new Thread() {
    		public void run() {
    			int i = 5;
    			while( i > 0) {
    				Node n = list.getHead().getNext();
    				if (n == list.getTail()) continue;
    				list.remove(n);
    				i--;
    			}
    			try {
					barrier.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (BrokenBarrierException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    	};
    	
    	thread1.start();
    	thread2.start();
    	barrier.await();
    	System.out.printf("Size: %d\n", list.getSize());
    	
    	  // Traverse from head to tail, exclude head and tail
        for (Node n = list.getHead().getNext(); n!=list.getTail(); n=n.getNext()) {
            System.out.printf("%d ", n.getData());
        }
        System.out.println();
        
        // Traverse from tail to head, exclude tail and head.
        for (Node n = list.getTail().getPrev(); n!=list.getHead(); n=n.getPrev()) {
            System.out.printf("%d ", n.getData());
        }
        listB.remove(list.getHead().getNext()); // Test if target belongs to List 
        
    }
}
